import 'package:ad_common/third_ad.dart';
import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

import 'google_ad_manager.dart';

/// FileName google_insert_ad
/// @Author zhuqingfang
/// @Date 2022/9/30 4:51 下午
/// @Description google insert ad
class GoogleInsertAd extends ThirdAd {
  GoogleInsertAd({required ThirdAdParams thirdAdParams})
      : super(thirdAdParams: thirdAdParams);
  InterstitialAd? _interstitialAd;

  @override
  void load() {
    if (!isSdkInit) {
      init();
    }
    _loadInsertAd();
  }

  @override
  void show() {
    _showInsertAd();
  }

  void _loadInsertAd() {
    InterstitialAd.load(
        adUnitId: thirdAdParams.placementId,
        request: const AdRequest(),
        adLoadCallback: InterstitialAdLoadCallback(
          onAdLoaded: (InterstitialAd ad) {
            // Keep a reference to the ad so you can show it later.
            _interstitialAd = ad;
            debugPrint('google $ad loaded.');
            thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adLoaded,
                'google insert ad placementID:${thirdAdParams.placementId} loaded');
          },
          onAdFailedToLoad: (LoadAdError error) {
            debugPrint('InterstitialAd failed to load: $error');
            thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adLoadFail,
                'google reward video ad placementID:${thirdAdParams.placementId} video load fail');
          },
        ));
  }

  void _showInsertAd(){
    if(_interstitialAd == null){
      thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adShowFail,
          'google insert ad placementID:${thirdAdParams.placementId}  show fail');
      return;
    }
    _interstitialAd?.fullScreenContentCallback = FullScreenContentCallback(
      onAdShowedFullScreenContent: (InterstitialAd ad) {
        debugPrint('%ad onAdShowedFullScreenContent.');
        thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adOnShow,
            'google insert ad placementID:${thirdAdParams.placementId} onShow');
      },
      onAdDismissedFullScreenContent: (InterstitialAd ad) {
        debugPrint('$ad onAdDismissedFullScreenContent.');
        thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adOnDismissed,
            'google insert ad placementID:${thirdAdParams.placementId} onDismiss');
        _interstitialAd = null;
        ad.dispose();
      },
      onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
        debugPrint('$ad onAdFailedToShowFullScreenContent: $error');
        thirdAdParams.thirdAdEventCallback(AdCallbackEvent.adShowFail,
            'google insert ad placementID:${thirdAdParams.placementId} show Fail');
        _interstitialAd = null;
        ad.dispose();
      },
      onAdImpression: (InterstitialAd ad) => debugPrint('$ad impression occurred.'),
    );
    _interstitialAd?.show();
  }
}
